package com.atmilan.quartz.utils.source;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.paolo.PaoloProduct;
import com.atmilan.quartz.model.entity.paolo.PaoloProductSku;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 功能描述: 处理源数据转换和计算
 * @Author: wangzh
 * @Date: 2023/2/8 17:25
 */
@Service
public class SourcePaoloProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 功能描述: 构建对象(paolo)
     * @Param: [product, skus]
     * @Return: com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest
     * @Author: wangzh
     * @Date: 2023/2/14 14:47
     */
    public StoreProductCrmebRequest buildPaoloProduct(PaoloProduct product, List<PaoloProductSku> skus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            // 轮播图
            JSONArray photos = JSONArray.parseArray(product.getPhotos());
            // 成本价
            BigDecimal erpPrice = product.getRetailPrice();
            // 售价
            PriceResult priceResult = priceUtil.eur2Rmb(product.getPrice());
            BigDecimal adjustPrice = priceResult.getPrice().divide(BigDecimal.valueOf(1.22), 0, RoundingMode.UP);
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getEnName, product.getBrand())
                    .eq(StoreBrand::getType, ProductTypeEnum.JULIAN)
                    .last("limit 1"));
            storeBrandService.unMatchBrand(buyerStoreBrand, null, product.getBrand(), ProductTypeEnum.JULIAN);
            StoreBrand storeBrand = null;
            if (null != buyerStoreBrand) {
                if (null != buyerStoreBrand.getSuperId()) {
                   storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                }
            } else {
                storeBrand = storeBrandService.getById(5429);
            }
            String barCode = BarCodeEnum.JULIAN.getCode() + product.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

            List<String> colorValueList = new ArrayList<>();
            List<String> sizeValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);

            for (PaoloProductSku sku : skus) {
                // value
                StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
                storeProductAttrValueRequest.setSourceSkuId(sku.getGtin());
                storeProductAttrValueRequest.setStock(sku.getStock());
                storeProductAttrValueRequest.setPrice(adjustPrice);
                if (photos.size() > 0) {
                    storeProductAttrValueRequest.setImage(photos.get(0).toString());
                }
                storeProductAttrValueRequest.setCost(adjustPrice);
                storeProductAttrValueRequest.setSourceCost(adjustPrice);
                storeProductAttrValueRequest.setBarCode(barCode);
                storeProductAttrValueRequest.setOtPrice(erpPrice);
                // 发货地（欧洲）
                storeProductAttrValueRequest.setTempId(StockAreaTempEnum.EUR.getTempId());
                List<String> suk = new ArrayList<>();
                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(product.getColor())){
                    linkedMap.put("颜色", product.getColor());
                    if (!colorValueList.contains(product.getColor())){
                        colorValueList.add(product.getColor());
                    }
                    suk.add(product.getColor());
                }
                if (StringUtils.isNotBlank(sku.getSize())){
                    linkedMap.put("尺寸", sku.getSize());
                    if (!sizeValueList.contains(sku.getSize())){
                        sizeValueList.add(sku.getSize());
                    }
                    suk.add(sku.getSize());
                }
                // suk
                storeProductAttrValueRequest.setSuk(String.join(",", suk));
                storeProductAttrValueRequest.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValueRequest);
            }
            // attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(sizeValueList)) {
                storeProductAttr.setAttrValues(String.join(",", sizeValueList));
                attrList.add(storeProductAttr);
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            //强制写一个 商户id 作为buyer商品标识
            productRequest.setMerId(CrmebMerchantEnums.JULIAN.getMerchantId());
            productRequest.setContent(product.getDescription());
            // 商品keyword
            productRequest.setKeyword(product.getSku());
            productRequest.setStoreInfo(product.getDescription());
            productRequest.setStoreName(product.getName());
            if (null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(erpPrice);
            productRequest.setCost(adjustPrice);
            productRequest.setSourceCost(adjustPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(StockAreaTempEnum.EUR.getTempId());

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier::getBarcode, BarCodeEnum.JULIAN)
                    .last("limit 1"));
            if (null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.JULIAN.getCode())
                    .eq(CategoryMatch::getOthCategoryId, product.getGenre())
                    .eq(CategoryMatch::getOthCategoryName, product.getType())
                    .eq(CategoryMatch::getOthCategoryType, product.getCategory())
                    .last("limit 1"));
            categoryMatchService.unMatchCategory(categoryMatch, product.getGenre(), product.getType(), product.getCategory(), CategoryTypeEnum.JULIAN);
            // 复制重量
            if (null != categoryMatch) {
                CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
                categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setImage(photos.get(0).toString());
            if (photos.size() > 0) {
                productRequest.setSliderImage(photos.toJSONString());
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.JULIAN.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setSeasonCode(product.getSeason());
            productRequest.setColorCode(product.getColor());
            productRequest.setComposition(product.getComposition());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }
}
